﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Blade.IO {
	public sealed class MemoryCursorStream : CursorStream {
		byte[] buffer;
		int offset;
		int count;
		bool writable;

		long position;

		public MemoryCursorStream(byte[] buffer, bool writable)
			: this(buffer, 0, buffer.Length, writable) {
		}

		public MemoryCursorStream(byte[] buffer, int offset, int count, bool writable) {
			this.buffer = buffer;
			this.offset = offset;
			this.count = count;
			this.writable = writable;
		}

		protected override int ReadCore(long position, byte[] buffer, int offset, int count) {
			Array.Copy(
				this.buffer,
				this.offset + position,
				buffer,
				offset,
				count
			);
			return count;
		}

		protected override void WriteCore(long position, byte[] buffer, int offset, int count) {
			if (!writable)
				throw new NotSupportedException();
			Array.Copy(
				buffer,
				offset,
				this.buffer,
				this.offset + position,
				count
			);
		}

		public override bool CanRead { get { return true; } }

		public override bool CanSeek { get { return true; } }

		public override bool CanWrite { get { return writable; } }

		public override void Flush() { }

		public override long Length { get { return count; } }

		public override long Position {
			get { return this.position; }
			set { this.position = value; }
		}
	}
}
